package info.nixbear.tgcms.admin.server;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.images.Image;
import com.google.appengine.api.images.ImagesService;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.api.images.Transform;

public class AdminUploadServlet extends HttpServlet {

	Logger logger = LoggerFactory.getLogger(AdminUploadServlet.class);
	
	private BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();

	private static final long serialVersionUID = -1999885731327138730L;
	
	public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
		ImagesService imagesService = ImagesServiceFactory.getImagesService();
	    Image oldImage = ImagesServiceFactory.makeImageFromBlob(new BlobKey(req.getParameter("blob-key")));
	    Transform resize = ImagesServiceFactory.makeResize(100, 100);
	    Image newImage = imagesService.applyTransform(resize, oldImage);
	    byte[] newImageData = newImage.getImageData();
		res.setContentType("image/jpeg");
		res.getOutputStream().write(newImageData);
	}

	public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException,
			IOException {

		Map<String, List<BlobKey>> blobs = blobstoreService.getUploads(req);

		if (blobs.isEmpty()) {
			return;
		}
		
		BlobKey blobKey = blobs.values().iterator().next().get(0);
		
//		ImagesService imagesService = ImagesServiceFactory.getImagesService();
//		String servingUrl = imagesService.getServingUrl(ServingUrlOptions.Builder.withBlobKey(blobKey));
		String servingUrl = "http://localhost/admin/upload?blob-key="+blobKey.getKeyString();
		
		JSONObject response = new JSONObject();
		try {
			response.put("blobKey", blobKey.getKeyString());
			response.put("servingUrl", servingUrl);
		} catch (JSONException e) {
			logger.error("JSON error", e);
		}
		res.getWriter().println(response.toString());
	}

}
